//
//  iComeApiManager.m
//  AFNetworking
//
//  Created by zhangrongwu on 2018/1/18.
//

#import "iComeApiManager.h"
#import "ICModuleHeaderFile.h"
#import "ICTools.h"
#import "MBProgressHUD+Tool.h"
#import "ICUser.h"
#import "NSString+Extension.h"
#import "ICCreateGroupManager.h"
#import "ICMessageForwardController.h"
#import "ICNavigationController.h"
#import "ICLoginNetworkManager.h"
#import "ICDatabaseManager.h"
#import "ICDefaultConfigManager.h"
#import "UIViewController+ICJSJump.h"
#import "ICSendMessageHelper.h"
#import "ICMessageHelper.h"
#import "ICMessageManager.h"
#import "ICMD5.h"

@interface iComeApiManager () <ICMessageForwardControllerDelegate>
@property (nonatomic, copy)successCallBack msgGetCallBack;

@property (nonatomic, assign)NSInteger connectCount;

@end
@implementation iComeApiManager

+(instancetype)instance {
    static iComeApiManager *manager;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[iComeApiManager alloc] init];
    });
    return manager;
}

- (instancetype)init {
    if (self = [super init]) {
        self.connectCount = 0;
    }
    return self;
}

/**
 * @注册tcp
 * @eid
 * @用户密码
 * @测试与生产环境
 * @回调处理 error data
 */
- (void)regiserApiUserName:(NSString *)userName passWord:(NSString *)passWord server:(ServerType)server :(successCallBack)success :(failCallBack)fail {
    if (server == Server_DEBUG) {// 测试
        self.url = @"http://10.39.35.11:88/";
        self.tcpUrl = @"10.39.35.11";
        self.tcprt = 89;
    } else if (server == Server_PRE_RELEASE){// 预生产
        self.url = @"http://eim.enn.cn/";
        self.tcpUrl = @"eim.enn.cn";
        self.tcprt = 81;
    } else {//生产
        self.url = @"http://im2.enn.cn/";
        self.tcpUrl = @"im2.enn.cn";
        self.tcprt = 81;
    }
    [[NSUserDefaults standardUserDefaults] setObject:userName forKey:@"iComeApiManagerUserName"];
    [[NSUserDefaults standardUserDefaults] setObject:passWord forKey:@"iComeApiManagerPassWord"];
    [[NSUserDefaults standardUserDefaults] setInteger:server forKey:@"iComeApiManagerIsDebug"];
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    
    if (![ICTools stringEmpty:token]) {
        [[ICDefaultConfigManager sharedInstance] initTCP];
        NSString *appDeviceId  = [NSString stringWithFormat:@"%@_%@%@",[ICUser currentUser].eId,[ICTools getDeviceTypeInfo],[ICTools getDeviceId]];
        NSLog(@"%@", [ICMD5 md5:appDeviceId]);
        if (success) {
            success(@{@"Alias":[ICMD5 md5:appDeviceId]});
        }
    } else {
        // 接口调用
        WEAKSELF
        [[ICLoginNetworkManager sharedInstance] loginLicensor:userName password:passWord success:^(NSDictionary *dic) {
            NSDictionary *data = [dic objectForKey:@"data"];
            NSString *token = [data objectForKey:@"token"];
            NSString *ticket = [data objectForKey:@"ticket"];
            NSDictionary *employee = [data objectForKey:@"employee"];
            
            [weakSelf checkLoginStatusFromEmployee:employee];
            [[ICDatabaseManager shareManager] createMessageTables];
            
            if (![ICTools stringEmpty:token]) {   // 保存token
                [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"Token"];
                [[NSUserDefaults standardUserDefaults] setObject:ticket forKey:@"JSTicket"];
                NSString *userId = [NSString stringWithFormat:@"%@",[employee objectForKey:@"eId"]];
                [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"user_Id"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [ICNetworkHelper setValue:token forHTTPHeaderField:@"token"];
                [ICUser saveCurrentUserInfor:employee];
                [ICTools setDownLoadImageToken:token];
                
                [[ICDefaultConfigManager sharedInstance] createDefaultGroups];
                [[ICDefaultConfigManager sharedInstance] initTCP];
            }
            NSString *appDeviceId  = [NSString stringWithFormat:@"%@_%@%@",[ICUser currentUser].eId,[ICTools getDeviceTypeInfo],[ICTools getDeviceId]];
            if (success) {
                success(@{@"Alias":appDeviceId});
            }
        } failure:^(NSError *error) {
          
            if (self.connectCount <= 5) {
                self.connectCount++;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self regiserApiUserName:userName passWord:passWord server:server :nil :nil];
                });
            } else {
                if (fail) {
                    fail(error.domain);
                }
            }
        }];
    }
    
    if ([[iComeApiManager instance].delegate respondsToSelector:@selector(registerAdaptItemClass)]) {
        NSArray *cellClassList = [[iComeApiManager instance].delegate registerAdaptItemClass];
        [[NSUserDefaults standardUserDefaults] setValue:cellClassList forKey:@"cellClassList"];
    }
}

// 新旧账号不同时：清除icome中旧用户数据
-(void)checkLoginStatusFromEmployee:(NSDictionary *)employee {
    NSString *oldUserId = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_Id"];
    NSString *newUserId = [NSString stringWithFormat:@"%@",[employee objectForKey:@"eId"]];
    if (![oldUserId isEqualToString:newUserId] && ![ICTools stringEmpty:oldUserId]) { // 新用户登录时 清除旧数据
        [ICTools clearAllLocateInfo];  // 清理用户聊天等本地存储信息
        // 用户信息清理
        [ICUser releaseUser];
    } else {
        NSLog(@"is old user ");
    }
}

/**
 * @打开消息列表
 * @来源控制器页面 self
 * @打开成功失败 error
 */
- (void)openChatList:(UIViewController *)fromViewC :(successCallBack)success :(failCallBack)fail {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url] || [ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    UIViewController *viewController =[[IComMediator sharedInstance] IComMediator_MessageVController:nil];
    [fromViewC.navigationController pushViewController:viewController animated:YES];
    if (success) {
        success(@"success");
    }
}
/**
 * @创建群组
 * @群组名称 @"测试群组名称" 默认使用时间戳
 * @用户列表 @[@"10045111", @"10045222", @"10045555"]
 * @来源控制器页面 self
 * @回调处理 gid string
 */
- (void)createGroupWithgName:(NSString *)gName eIds:(NSArray *)eIds fromViewC:(UIViewController *)fromViewC :(successCallBack)success :(failCallBack)fail {
    if ([ICTools stringEmpty:gName]) {
        gName = [NSString currentName];
    }
    
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    NSDictionary *param =@{@"eId":[ICUser currentUser].eId,
                           @"eIds":eIds,
                           @"eName":[ICUser currentUser].eName,
                           @"gName":gName};
    
    NSMutableArray * mutableArray = [eIds mutableCopy];
    NSString *tempString = [mutableArray componentsJoinedByString:@","];
    if([tempString rangeOfString:[ICUser currentUser].eId].location !=NSNotFound)
    {
        if([mutableArray count] > 1){
            [mutableArray removeObject:[ICUser currentUser].eId];
            NSMutableDictionary * newdic = [[NSMutableDictionary alloc]init];
            [newdic setDictionary:param];
            [newdic setValue:mutableArray forKey:@"eIds"];
            [ICCreateGroupManager createMultGroupWith:newdic Handle:^(ICGroup *group) {
                if (success) {
                    success(group.gId);
                }
            }];
        } else{
            if (fail) {
                fail(@"请至少添加一个用户");
            }
        }
    }
    else
    {
        [ICCreateGroupManager createMultGroupWith:param Handle:^(ICGroup *group) {
            if (success) {
                success(group.gId);
            }
        }];
    }
}
- (void)openChatWith:(NSString *)eId fromViewC:(UIViewController *)fromViewC :(successCallBack)success :(failCallBack)fail {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    
    if ([ICTools stringEmpty:eId]) {if (fail) {fail(@"eId不能为空");}return;}
    //双人会话
    NSDictionary *param = @{@"eId":[ICUser currentUser].eId,
                            @"eName":[ICUser currentUser].eName,
                            @"otherId":eId};
    [ICCreateGroupManager createTwoGroupWith:param Handle:^(ICGroup *group) {
        if (group) {
            if (fromViewC) {
                ICChatViewController *vc = [[ICChatViewController alloc] init];
                vc.group = group;
                [fromViewC.navigationController pushViewController:vc animated:YES];
            }
        }
        if (success) {
            success(@{@"gId":group.gId});
        }
    }];
}

/**
 * @打开某个会话窗口
 * @群组id
 * @需要发送的消息体
 * @来源控制器页面 self
 */
- (void)openChatWindowWithgId:(NSString *)gId message:(IMMessage *)message fromViewC:(UIViewController *)fromViewC :(successCallBack)success :(failCallBack)fail {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    
    if ([ICTools stringEmpty:gId]) {
        if (fail) {fail(@"gId不为空");}return;
    }
    
    if (![ICMessageDatabase isGroupExisted:gId]) {
        if (fail) {fail(@"群组不存在");}return;
    }
    
    if (![ICTools stringEmpty:message.type]) {
        // 发送消息
        [self cgeateMessageFrameWith:message to:gId :^(ICMessageFrame *messageF) {
            ICMessageModel *messageModel = messageF.model;
            ICMessage *message = [ICMessageHelper createSendMessageF:messageF
                                                             Message:messageModel.message.type
                                                             content:messageModel.message.content
                                                             fileKey:messageModel.message.fileKey
                                                                from:[ICUser currentUser].eId
                                                                  to:gId
                                                                 lnk:messageModel.message.lnk
                                                              status:nil];
            message.localMsgId = [ICMessageHelper localMessageId:message.content];
            message.messageId = message.localMsgId;
            message.date = [ICMessageHelper currentMessageTime];
            message.deliveryState = ICMessageDeliveryState_Delivering;
            
            [self saveMessage:messageModel messageId:message.messageId gId:gId];
            [ICSendMessageHelper sendMessageWithObject:[ICMessageHelper createSendParamWithMessage:message]
                                            identifier:message.localMsgId
                                               Success:^(id object, id other) {
                                                   if (success) {
                                                       success(@"send message success");
                                                   }
                                               } Failure:^(NSError *error, id other) {
                                                   if (fail) {fail(error.domain);}
                                               }];
            [ICMessageDatabase getGroupWithgId:gId finish:^(NSArray *array, NSError *error) {
                if (fromViewC) {
                    ICGroup *group = [array lastObject];
                    UIViewController *viewController =[[IComMediator sharedInstance] IComMediator_ChatViewController: @{@"group":group}];
                    [fromViewC.navigationController pushViewController:viewController animated:YES];
                }
            }];
        }];
    } else {
        [ICMessageDatabase getGroupWithgId:gId finish:^(NSArray *array, NSError *error) {
            if (array.count > 0) {
                if (success) {success(@"send message success");}
                if (fromViewC) {
                    ICGroup *group = [array lastObject];
                    UIViewController *viewController =[[IComMediator sharedInstance] IComMediator_ChatViewController: @{@"group":group}];
                    [fromViewC.navigationController pushViewController:viewController animated:YES];
                }
            } else {
                if (fail) {fail(error.domain);}
            }
        }];
    }
}

- (void)saveMessage:(ICMessageModel *)messageModel
          messageId:(NSString *)messageId
                gId:(NSString *)gId {
    messageModel.message.deliveryState = ICMessageDeliveryState_Delivering;
    messageModel.message.to = gId;
    messageModel.isSender = YES;
    messageModel.message.from  = [ICUser currentUser].eId;
    messageModel.message.status = ICMessageStatus_read;
    // 失败之后，给一个本地的消息Id，重发的时候还需要更改
    messageModel.message.messageId = messageId;
    // 失败后的时间是本地时间
    NSInteger currentDate = [ICMessageHelper currentMessageTime];
    messageModel.message.date = currentDate;
    [ICMessageDatabase saveMessage:messageModel];
}

/**
 * @分享信息到iCome SDK
 * @需要发送的消息体 不需要填写to字段
 * @来源控制器页面 self
 * @分享回调逻辑
 */
- (void)shareToChatWithMessage:(IMMessage *)message fromViewC:(UIViewController *)fromViewC :(successCallBack)success :(failCallBack)fail {
    if (!message) {
        if (fail) {fail(@"参数错误");}return;
    }
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    // 半成品逻辑
    [self cgeateMessageFrameWith:message to:@"" :^(ICMessageFrame *messageF) {
        
        ICMessageForwardController *vc = [[ICMessageForwardController alloc] init];
        vc.delegate = self;
        vc.name = @"分享";
        vc.messageModelsArray = @[messageF];
        
        ICNavigationController * nav = [[ICNavigationController alloc] initWithRootViewController:vc];
        [fromViewC presentViewController:nav animated:YES completion:nil];
    }];
}

- (void)cgeateMessageFrameWith:(IMMessage *)message to:(NSString *)gId :(void(^)(ICMessageFrame *messageF))callBack
{
    NSDictionary *dict = @{@"txt":message.txt,
                           @"fr":[ICUser currentUser].eId,
                           @"to":gId,
                           @"lnk":@"",
                           @"type":message.type,
                           @"key":[message.data jsonString]
                           };
    [ICMessageHelper messageTypeWithMessage:dict finished:^(ICMessageFrame *messageF) {
        [ICMessageDatabase saveMessage:messageF.model]; // 统一存储消息
        if (callBack) {
            callBack(messageF);
        }
    }];
}

/**
 * @获取用户头像url
 * @员工id
 * @return url string
 */
- (NSString *)getEmpPhoto:(NSString *)eId {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {
        [MBProgressHUD showError:@"未注册"];
        return @"";
    }
    
    if ([ICTools stringEmpty:eId]) {
        [MBProgressHUD showError:@"eId不能为空"];
        return @"";
    }
    return [NSString stringWithFormat:@"%@fileserver/photo/getEmpPhoto?eId=%@",self.url, eId];
}

- (void)appendUsers:(NSString *)gId eIds:(NSArray *)eIds :(successCallBack)success :(failCallBack)fail {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    
    if ([ICTools stringEmpty:gId]) {
        if (fail) {fail(@"gid不为空");}return;
    }
    
    if (![ICMessageDatabase isGroupExisted:gId]) {
        if (fail) {fail(@"群组不存在");}return;
    }
    
    NSDictionary *dict = @{@"gId":gId,
                           @"eIds":eIds};
    [[ICSocketRequestManager sharedInstance] appendUserWithObject:dict Success:^(id response) {
        NSDictionary *data = [response objectForKey:@"data"];
        ICGroup *group = [ICGroup mj_objectWithKeyValues:data];
        if ([group.gType isEqualToString:@"1"]) {
            // 双人组新创建了组
            [[NSNotificationCenter defaultCenter] postNotificationName:NotificationDidCreatedConversation object:nil];
            for (ICUser *user in group.userList) {
                if (![user.eId isEqualToString:[ICUser currentUser].eId]) {
                    group.gName  = user.eName;
                    break;
                }
            }
        }
        group.valid = 1; // 默认肯定可用
        group.busy = 0;  // 默认是0，不免打扰
        group.lastMsgTime = [ICMessageHelper currentMessageTime];
        if ([[data objectForKey:@"master"] isEqualToString:[ICUser currentUser].eId]) {
            group.master = 1;
        } else {
            group.master = 0;
        }
        [ICMessageDatabase saveGroup:group];
        if (success) {
            success(@"人员添加成功");
        }
    } Failure:^(NSError *error, id other) {
        if (fail) {
            fail(error.domain);
        }
    }];
}

- (void)destroy:(successCallBack)success :(failCallBack)fail {
    [ICTools outLogIn];
    if (success) {
        success(@"success");
    }
}

- (void)pushWebViewControllerURL:(NSString *)URL
                       fromViewC:(UIViewController *)fromViewC
                        animated:(BOOL)animated {
    [fromViewC pushCustomViewControllerURL:URL
                        fromViewController:fromViewC
                                  animated:YES];
}

- (void)msgGet:(successCallBack)success :(failCallBack)fail {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    self.msgGetCallBack = success; // 新消息回调
    [self updateUnreadMsg];
}

- (void)getRrecentPersion:(successCallBack)success :(failCallBack)fail {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    [ICMessageDatabase recentContactUsers:^(NSArray *array, NSError *error) {
        NSMutableArray *list = [[NSMutableArray alloc] init];
        for (ICUser *user in array) {
            [list addObject:@{@"eId":user.eId,
                              @"eName":user.eName,
                              @"photoId":user.photoId}];
        }
        if (success) {success(list);};
    }];
}

- (void)updateUnreadMsg {
    if (self.msgGetCallBack) {
        [[ICMessageManager instance] getMessageGroups:^(NSMutableArray *array) {
            NSInteger unReadCount = 0;
            ICGroup *ugroup = [[ICGroup alloc] init];
            for (ICGroup *group in array) {
                if (group.unReadCount > 0) {
                    ugroup = group;
                }
                unReadCount = unReadCount+group.unReadCount;
            }
            if ([iComeApiManager instance].msgGetCallBack) {
                NSString *fr = ugroup.lastMsgeName;
                NSString *to = ugroup.gName;
                NSString *txt = ugroup.lastMsgTxt;
                if ([ICTools stringEmpty:ugroup.lastMsgTxt]) {
                    txt = ugroup.lastMsgString;
                }
                if ([ugroup.lastChangeGroupUserId isEqualToString:[ICUser currentUser].eId]) {
                    fr = [ICUser currentUser].eName;
                }
                [iComeApiManager instance].msgGetCallBack(@{@"msg":@{@"fr":fr,
                                                                     @"to":to,
                                                                     @"txt":txt},
                                                            @"unread":@(unReadCount)});
            }
        }];
    }
}

/**
 * @获取所有的群组
 * @ 2 为多人组 1为双人组
 */
- (void)getGroupsWithgType:(NSInteger)type :(successCallBack)success :(failCallBack)fail {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    
    [ICMessageDatabase getGroupsWithgType:(ICGroupType)type Finish:^(NSArray *array, NSError *error) {
        if (array.count == 0) { // 数据异常
            NSLog(@"无该类型群组");
        }
        NSArray *dictArray = [NSArray mj_keyValuesArrayWithObjectArray:array];
        if (success) {
            success(dictArray);
        }
    }];
}

/**
 * @获取某个群组所有人员
 * @gid群组id
 */
- (void)getUsersWithgId:(NSString *)gId :(successCallBack)success :(failCallBack)fail {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"Token"];
    if ([ICTools stringEmpty:self.url]||[ICTools stringEmpty:token]) {if (fail) {fail(@"打开失败，未注册");}return;}
    
    if ([ICTools stringEmpty:gId]) {
        if (fail) {fail(@"gId不为空");}return;
    }
    [ICMessageDatabase getUsersWithGroupId:gId finish:^(NSArray *array, NSError *error) {
        if (array.count == 0) { // 数据异常
            NSLog(@"群组无人员");
        }
        NSArray *dictArray = [NSArray mj_keyValuesArrayWithObjectArray:array];
        if (success) {
            success(dictArray);
        }
    }];
}
@end

